﻿/*
The MIT License (MIT)
Copyright (c) 2013 kaveh.shahbazian@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), 
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 
IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Buddy
{
    /// <summary>
    /// simple command line argument parser for 80% of my needs
    /// </summary>
    public class Args
    {
        const string ARG_TEMPLATE = "(?<parameter>(?<prefix>^-{1,2}|^/)(?<switch>[^=:]+)(?<splitter>[=:]{0,1})(?<value>.*$))|(?<argument>.*)";
        readonly List<Arg> _args;

        public Args() { _args = Parser(Environment.GetCommandLineArgs()); }
        public Args(string[] args) { _args = Parser(args); }

        public string this[string @switch]
        {
            get
            {
                if (string.IsNullOrWhiteSpace(@switch)) throw new ArgumentNullException("@switch");

                var @param = (from a in _args where a.IsParameter && string.Compare(a.Switch, @switch, true) == 0 select a).FirstOrDefault();
                if (@param != null)
                {
                    if (!string.IsNullOrWhiteSpace(@param.Value) || !string.IsNullOrWhiteSpace(@param.Splitter)) return @param.Value;
                    return @param.Switch;
                }

                @param = (from a in _args where !a.IsParameter && string.Compare(a.Value, @switch, true) == 0 select a).FirstOrDefault();
                if (@param != null) return @param.Value;

                return null;
            }
        }
        public string[] this[string @switch, int maxNumberOfArguments]
        {
            get
            {
                if (string.IsNullOrWhiteSpace(@switch)) throw new ArgumentNullException("@switch");

                maxNumberOfArguments = maxNumberOfArguments == -1 ? int.MaxValue - 1 : maxNumberOfArguments;

                Arg @param = null;
                var args = new List<Arg>();

                var part1 = _args.SkipWhile(p => string.Compare(p.Switch, @switch, true) != 0);
                @param = part1.Take(1).FirstOrDefault();
                if (@param != null)
                {
                    args = part1.Skip(1).TakeWhile(a => !a.IsParameter).ToList();
                    args = args.Take(maxNumberOfArguments).ToList();
                }

                if (@param != null)
                {
                    return (from a in args select a.Value).ToArray();
                }
                else
                    return null;
            }
        }

        static List<Arg> Parser(string[] args)
        {
            if (args == null || args.Length == 0) return new List<Arg>();

            Func<Capture, string> getVal = c => { return c == null ? null : c.Value; };

            var result = new List<Arg>();

            foreach (var a in args)
            {
                var m = Regex.Match(a, ARG_TEMPLATE);
                if (m.Groups["parameter"] != null && m.Groups["parameter"].Success)
                {
                    result.Add(new Arg(
                        getVal(m.Groups["prefix"]),
                        getVal(m.Groups["switch"]),
                        getVal(m.Groups["splitter"]),
                        getVal(m.Groups["value"])));
                }
                else
                {
                    result.Add(new Arg(getVal(m.Groups["argument"])));
                }
            }

            return result;
        }

        class Arg
        {
            /// <summary>
            /// is a parameter or an argument
            /// </summary>
            public bool IsParameter { get; private set; }
            public string Prefix { get; private set; }
            public string Switch { get; private set; }
            public string Splitter { get; private set; }
            public string Value { get; private set; }

            private Arg() { }
            public Arg(
                string prefix,
                string switch_,
                string splitter,
                string val)
            {
                this.Prefix = prefix;
                this.Switch = switch_;
                this.Splitter = splitter;
                this.Value = val;
                this.IsParameter = true;
            }
            public Arg(
                string val)
            {
                this.Value = val;
                this.IsParameter = false;
            }

            public override string ToString()
            {
                return this.IsParameter ?
                    string.Format("{0}{1}{2}{3}",
                        Prefix ?? string.Empty,
                        Switch ?? string.Empty,
                        Splitter ?? string.Empty,
                        Value ?? string.Empty) :
                    string.Format("{0}", Value ?? string.Empty);
            }
        }
    }
}
